function [L, A, B] = rgb_to_lab(r, g, b)
%RGB_TO_LAB Converts RGB color to LAB color
%
%   [L, A, B] = RGB_TO_LAB(r, g, b);
%
%       converts colors represented with R, G, B components into 
%       LAB components.
%
%       Note: the inputs should have been normalized to [0, 1] range.
%

% Created by Dahua Lin, on Mar 8, 2012
%

%% main

T = 0.008856;

X = (0.412453 * r + 0.357580 * g + 0.180423 * b) / 0.950456;
Y = 0.212671 * r + 0.715160 * g + 0.072169 * b;
Z = (0.019334 * r + 0.119193 * g + 0.950227 * b) / 1.088754;
   
XT = X > T;
YT = Y > T;
ZT = Z > T;

fX = XT .* X.^(1/3) + (~XT) .* (7.787 .* X + 16/116);

% Compute L
Y3 = Y.^(1/3); 
fY = YT .* Y3 + (~YT) .* (7.787 .* Y + 16/116);
L  = YT .* (116 * Y3 - 16.0) + (~YT) .* (903.3 * Y);

fZ = ZT .* Z.^(1/3) + (~ZT) .* (7.787 .* Z + 16/116);

% Compute a and b
A = 500 * (fX - fY);
B = 200 * (fY - fZ);

